package com.ctrlcar.giftrecord.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctrlcar.giftrecord.mapper.GiftBookMapper;
import com.ctrlcar.giftrecord.pojo.GiftBook;

import com.ctrlcar.giftrecord.pojo.ReceiveGift;
import com.ctrlcar.giftrecord.pojo.model.Result;
import com.ctrlcar.giftrecord.service.GiftBookService;
import com.ctrlcar.giftrecord.service.ReceiveGiftService;
import com.ctrlcar.giftrecord.vo.GiftBookListVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
* @author
* @description 针对表【gift_book】的数据库操作Service实现
* @createDate 2025-03-26 16:43:36
*/
@Service
public class GiftBookServiceImpl extends ServiceImpl<GiftBookMapper, GiftBook>
    implements GiftBookService {
    @Resource
    private ReceiveGiftService receiveGiftService;

    /**
     * 根据用户id获取list
     * @param userId
     * @return
     */
    @Override
    public Result<List<GiftBookListVo>> getGiftBookList(Integer userId) {
        LambdaQueryWrapper<GiftBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GiftBook::getUserId,userId);
        List<GiftBook> list = list(queryWrapper);
        List<GiftBookListVo> giftBookListVos = new ArrayList<>();
        for (GiftBook giftBook : list){
            GiftBookListVo giftBookListVo = BeanUtil.copyProperties(giftBook, GiftBookListVo.class);
            //根据bookId查询relativeList
            List<ReceiveGift> relativeList = receiveGiftService.list(
                    new LambdaQueryWrapper<ReceiveGift>().eq( ReceiveGift::getBookId, giftBook.getBookId()));
            //统计人数跟金额放入giftBookListVo
            giftBookListVo.setRelativeNum(relativeList.size());
            BigDecimal num = new BigDecimal(0);
            for (ReceiveGift receiveGift : relativeList){
                num = num.add(receiveGift.getGiftMoney());
            }
            giftBookListVo.setMoney(num);
            giftBookListVos.add(giftBookListVo);
        }
        return Result.success(giftBookListVos);
    }

    /**
     * 根据id删除本子
     * @param bookId
     * @return
     */
    @Override
    public Result<String> delBookById(Integer bookId) {
//        先根据bookid查询所有送礼记录
        List<ReceiveGift> receiveGiftList = receiveGiftService.list(
                new LambdaQueryWrapper<ReceiveGift>().eq(ReceiveGift::getBookId, bookId));
        for (ReceiveGift receiveGift : receiveGiftList){
            receiveGiftService.removeById(receiveGift.getReceiveId());
        }
        if (removeById(bookId)){
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
}




